import os
import flask
import xml.etree.ElementTree as ET
import time


'''
<?xml version="1.0"?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
<cXML payloadID="958075346970@www.bigbuyer.com " timestamp="2005-06-14T12:57:09-07:00">
 <Header>
 <From>
 <Credential domain="NetworkID">
 <Identity>AN01000002792</Identity>
 </Credential>
 </From>
 <To>
 <Credential domain="DUNS">
 <Identity>12345678</Identity>
 </Credential>
 </To>
 <Sender>
 <Credential domain="AribaNetworkUserId">
 <Identity>sysadmin@ariba.com/Identity>
 <SharedSecret>abracadabra</SharedSecret>
 </Credential>
 <UserAgent>Ariba Buyer 8.2</UserAgent>
 </Sender>
 </Header>
 <Request>
 <PunchOutSetupRequest operation="create">
 <BuyerCookie>1J3YVWU9QWMTB</BuyerCookie>
 <Extrinsic name="CostCenter">610</Extrinsic>
 <Extrinsic name="User">jpicard</Extrinsic>
 <BrowserFormPost>
 <URL>http://bigbuyer.com:3377/punchout</URL>
 </BrowserFormPost>
 <SupplierSetup>
 <URL>https://punchout.workchairs.com/PunchOutServlet</URL>
 </SupplierSetup>
 <ShipTo>
 <Address addressID="001">
 <Name xml:lang="en">BigBuyer Headquarters</Name>
 <PostalAddress>
 <DeliverTo>Jean Picard</DeliverTo>
 <Street>1565 Pine, MS A.2</Street>
 <City>New York</City>
 <State>NY</State>
 <PostalCode>01043</PostalCode>
 <Country isoCountryCode="US">United States</Country>
 </PostalAddress>
 </Address>
 </ShipTo>
 <Contact>
 <Name>jpicard</Name>
 </Contact>
 <SelectedItem>
 <ItemID>
 <SupplierPartID>54543</SupplierPartID>
 </ItemID>
 </SelectedItem>
 </PunchOutSetupRequest>
 </Request>
</cXML>
'''

global punchout_setup_url ,BrowserFormPost_url 
punchout_setup_url = 'https://ph-tt.kao1kao.com/index.html'
BrowserFormPost_url = ''

app = flask.Flask(__name__,static_url_path='/')
# recveive post request
@app.route('/api/pc/setup', methods=['POST'])
def setupPunchoutRequest():
    global punchout_setup_url ,BrowserFormPost_url 
    # 读取请求body 并存储到本地xml文件
    t = time.time()
    #格式化为 2020-08-03 11:40:00 形式
    timeStruct = time.localtime(t)
    filename = 'static/punchout/{}.xml'.format(time.strftime('%Y-%m-%d-%H-%M-%S',timeStruct))
    with open(filename, 'wb') as f:
        f.write(flask.request.data)
        f.close()
    # 读取本地xml文件并解析xml文件获取url节点数据
    el_tree = ET.parse(filename)
    el_tree_root = el_tree.getroot()
    pco_request = el_tree_root.find('Request')
    BrowserFormPost_url = pco_request.find('PunchOutSetupRequest').find('BrowserFormPost').find('URL').text
    # 格式化时间为 YYYY-MM-DDThh:mm:ss-hh:mm                           
    timestamp = time.strftime('%Y-%m-%dT%H:%M:%S%z',timeStruct)
    
    res_text = '''
    <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
    <cXML payloadID="{}@www.workchairs.com" timestamp="{}">
        <Response>
        <Status code="200" text="success"/>
            <PunchOutSetupResponse>
                <StartPage>
                    <URL>{}</URL>
                </StartPage>
            </PunchOutSetupResponse>
        </Response>
    </cXML>
    '''.format(t,timestamp,punchout_setup_url)
    return res_text, 200, {'Content-Type': 'text/xml'}
    # 返回响应
# supplier punchout url
@app.route('/api/spsite', methods=['GET'])
def spsite():
    global punchout_setup_url
    return punchout_setup_url, 200, {'Content-Type': 'text/plain'}

# browser form post url
@app.route('/api/bpurl', methods=['GET'])
def browserformpost():
    global BrowserFormPost_url
    return BrowserFormPost_url, 200, {'Content-Type': 'text/plain'}

@app.route('/pc', methods=['GET'])
def list_file():
    folder = 'static/punchout/'
    file_list = []
    for i in os.listdir(folder):
        file_list.append(i)
    # 拼接字符串數組
    res_text = ''
    for i in file_list:
        res_text += '<a href="/punchout/{}">{}</a><br>'.format(i, i)
    return res_text, 200, {'Content-Type': 'text/html'}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3377, debug=True)
